// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

async function get(id) {
  const db = cloud.database()
  return db.collection('post').where({
    _id: id,
    isValid: 1,
  }).get()
}

async function list({openid, visibleRange, s, page, size}) {
  const skip = (page - 1) * size
  const db = cloud.database()
  const _ = db.command
  const chain = [
    {isValid: 1,}
  ]
  if (openid) {
    chain.push({
      openid
    })
  } 
  if (visibleRange) {
    chain.push({
      visibleRange
    })
  }
  if (s) {
    chain.push(_.or([
      {
        nickName: db.RegExp({
          regexp: s,
          options: 'i'
        })
      },
      {
        title: db.RegExp({
            regexp: s,
            options: 'i'
        })
      },
      {
        labels: s
      }
    ]))
  }
  return db.collection('post').where(_.and(chain))
  .orderBy('topTime', 'desc')
  .skip(skip)
  .limit(size)
  .get()
}

async function insert({user, ...rest}) {
  const { OPENID } = cloud.getWXContext()
  const db = cloud.database()
  const _ = db.command
  try {
    const result = await db.runTransaction(async transaction => {
      const data = {
        ...rest,
        openid: user.openid || OPENID,
        nickName: user.nickName,
        avatarUrl: user.avatarUrl,
        createdTime: db.serverDate(),
        updatedTime: db.serverDate(),
        topTime: db.serverDate(), //置顶时间
        isValid: 1, // 逻辑删除
        status: 0, // 
      }

      const {_id} = await transaction.collection('post').add({
        data
      })
      await transaction.collection('user').doc(user._id).update({
        data: {
          labels: user.labels
        }
      })
      return {
        ...data,
        _id
      }
    })
    return {
      code: 0,
      data: result
    }
  } catch (e) {
    console.error(`insert post error:`, e)
    return {
      code: 1,
      data: e,
      msg: '发布失败'
    }
  }
}
async function update(data) {
  const db = cloud.database()
  const { _id, ...rest} = data
  if (rest.topTime) {
    rest.topTime = db.serverDate()
  }
  return db.collection('post').doc(_id).update({
    data:{
      ...rest,
      updatedTime: db.serverDate(),
    }
  })
}

async function remove(id) {
  const db = cloud.database()
  return db.collection('post').doc(id).remove()
}
// 云函数入口函数
exports.main = async ({action, data}) => {
 
  const func = {
    get,
    list,
    insert,
    update,
    remove,
  }[action]
  if (func) return func(data)
}
